package org.jeecg.common.util.mputil;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.common.util.auto_wrapper.AutoWhereUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 级联操作
 * p是主表c是子表
 *
 * @author zjarlin
 * @since 2023/2/26 09:18
 */
//@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MpUtil1<P> {

    protected IService<P> ps;

    public static <P> MpUtil1<P> of(IService<P> ps) {
        return new MpUtil1<>(ps);
    }


    /**
     * 只要数据库不存在的
     */
    public Collection<P> checkExists(Collection<P> collection) {
        if (CollUtil.isEmpty(collection)) {
            return new ArrayList<>();
        }
        Class<P> aClass = (Class<P>) collection.iterator().next().getClass();
        return collection.stream().filter(e -> {
//            根据实体中所有除了id以外的字段查一遍
            LambdaQueryWrapper<P> pLambdaQueryWrapper = AutoWhereUtil.lambdaQueryByField(aClass, e, true);
            long count = ps.count(pLambdaQueryWrapper);
            return count <= 0;
        }).collect(Collectors.toSet());
    }
        public boolean isExist(P p) {
            if (Objects.isNull(p)) {
                return false;
            }
            Class<P> entityClass = ps.getEntityClass();
//            根据实体中所有除了id以外的字段查一遍
            LambdaQueryWrapper<P> pLambdaQueryWrapper = AutoWhereUtil.lambdaQueryByField(entityClass, p, true);
            long count = ps.count(pLambdaQueryWrapper);
            return count > 0;
    }



}
